package com.masteringwave.wp;

import java.util.logging.Logger;

import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

@SuppressWarnings("serial")
public class WPRobotServlet extends AbstractRobotServlet {
	  private static final Logger log = Logger.getLogger("Robot");

	  private String ownname = "wp-bot@appspot.com";
  
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		
		// when the Robot is added publish to the robot
		if (bundle.wasSelfAdded()) {

			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.append(ownname+ " added version " +this.getVersion() +" \n");
			textView.appendMarkup("\n <a href=\"http://masteringwave.com/\">MasteringWave</a> <br />");
			textView.append("\n");
			String rootText = wavelet.getRootBlip().getDocument().getText();
			// find the first line, which will be the title to the blog
			String firstLine ;
			if(rootText.indexOf("\n")>0){
				firstLine = 	rootText.substring(0,rootText.indexOf("\n"));
			}else{
				firstLine = rootText;
			}
			textView.append( uploadWave(firstLine, wavelet.getWaveId()));
		}
		 

	}
	
	private String uploadWave(String title, String waveID){
		   String sXmlRpcURL = "http://wp-bot.masteringwave.com/xmlrpc.php";
		      String sUsername = "wave";
		      String sPassword = "<SECRET>";
		 
		      // Hard-coded blog_ID
		      String blog_ID = "1";
		 

		      // XML-RPC method
		      String sXmlRpcMethod = "metaWeblog.newPost";
		      // the content of the blog
		      String sContent = "[wave id=\""+waveID+"\" bgcolor=\"#ffffff\"]";

			      // Try block to create the upload
		      try
		      {
		        Wordpress wp = new Wordpress(sUsername, sPassword, sXmlRpcURL);
			      Page newPost = new Page();
			      newPost.setTitle(title);
			      newPost.setDescription(sContent);
			      newPost.setWp_author(sUsername);
			      String resultId = wp.newPost(newPost, "draft");
			      return wp.getPost(Integer.parseInt(resultId)).getPermaLink();
		      }
		      catch( Exception e )
		      {
		       return e.toString(); 
		      }
	}
}